package com.iraeta.service.basic.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iraeta.api.HikCameraApi;
import com.iraeta.api.HikRegionApi;
import com.iraeta.entity.basic.HikCamera;
import com.iraeta.entity.basic.HikRegion;
import com.iraeta.mapper.basic.HikCameraMapper;
import com.iraeta.service.basic.IHikCameraService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iraeta.service.basic.IHikRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 海康的摄像头表 服务实现类
 * </p>
 *
 * @author chenbin
 * @since 2024-01-11
 */
@Service
public class HikCameraServiceImpl extends ServiceImpl<HikCameraMapper, HikCamera> implements IHikCameraService {
    @Autowired
    IHikRegionService hikRegionServicel;
    @Autowired
    HikCameraApi cameraApi;

    @Override
    public HikCamera getHikCamera(String indexCode) {
        QueryWrapper<HikCamera> qw = new QueryWrapper<>();
        qw.eq("indexcode", indexCode);
        return baseMapper.selectOne(qw);
    }

    @Override
    public void addEditHikCamera(HikCamera hikCamera) {
        HikCamera hikCameraDb = this.getHikCamera(hikCamera.getIndexcode());
        if(hikCameraDb == null){
            baseMapper.insert(hikCamera);
        }else {
            hikCamera.setId(hikCameraDb.getId());
            baseMapper.updateById(hikCamera);
        }
    }

    /*从hikisc平台 接口更新HikCamera表数据*/
    @Override
    public void updateHikCameraFromHikIsc() throws  Exception {
        HikRegion rootHikRegion = hikRegionServicel.getRootHikRegion();
        JSONArray regionJSONArray = cameraApi.getCamera(rootHikRegion.getIndexcode());
        for(int i = 0; i<regionJSONArray.size(); i++){
            JSONObject regionJSONObject = regionJSONArray.getJSONObject(i);
            String name = regionJSONObject.getString("name");
            String indexCode = regionJSONObject.getString("indexCode");
            String regionIndexCode = regionJSONObject.getString("regionIndexCode");
            String regionPathName = regionJSONObject.getString("regionPathName");
            int sort = regionJSONObject.getIntValue("sort");
            HikCamera hikCamera = new HikCamera(name, indexCode, regionIndexCode, regionPathName, sort);
            hikCamera.setTreatytype(regionJSONObject.getString("treatyType"));
            hikCamera.setTranstype(regionJSONObject.getString("transType"));
            this.addEditHikCamera(hikCamera);
        }
    }

    @Override
    public List<HikCamera> listRegionCamera(String indexCode, String name) {
        return baseMapper.listRegionCamera(indexCode, name);
    }
}
